import requests
import time
import os 


SERVER_ADDRESS = 'http://127.0.0.1:5000/'
LOCAL_DIRECTORY = "D:\\JSONData\\H_SCAN\\"

def upload_file_with_auth(url, username, password, files_to_sync):
    
    for filename in files_to_sync:
    # 创建一个会话对象
        session = requests.Session()

        # 设置认证信息
        session.auth = (username, password)
        file_synced = False

        for _ in range(3):
            filename_path = os.path.join(LOCAL_DIRECTORY, filename)
            file_size = os.path.getsize(filename_path)
            uploaded_bytes = 0

            with open(filename_path, 'rb') as file:
                while True:
                    chunk = file.read(819200)
                    if not chunk:
                        # 读取到文件末尾，上传剩余部分
                        chunk = file.read()
                        if not chunk:
                            break

                    response = session.post(url, files={'file': (filename, chunk)})
                    uploaded_bytes += len(chunk)
                    progress = uploaded_bytes / file_size * 100
                    print(f"{filename} 上传进度：{progress:.2f}%")

            if response.status_code == 200:
                print('文件上传成功')
                file_synced = True
                break
            else:
                print('文件上传失败 %s, 正在重试..' % response)

        if not file_synced:
            print(f"文件 {filename} 在三次尝试后同步失败。停止同步过程。")
            break

        time.sleep(10)
        

# 获取服务器端文件结构
def get_server_files():
    response = requests.get(f"{SERVER_ADDRESS}/list_files")
    return response.json()

# 获取本地目录结构
def get_local_files():
    file_list = []
    for root, dir, files in os.walk(LOCAL_DIRECTORY):
        for file in files:
            file_list.append(os.path.relpath(os.path.join(root, file), LOCAL_DIRECTORY))
    return file_list

if __name__ == "__main__":
    local_files = get_local_files()
    server_files = get_server_files()

    files_to_sync = [file for file in local_files if file not in server_files]

    # 示例用法
    upload_file_with_auth(f'{SERVER_ADDRESS}/sysnc_upload', 'sumz', 'Sumz', files_to_sync)